import paramiko  
from scp import SCPClient 
import os
import stat
def scp_download(hostname, port, username, password, remote_path, local_path):  
    # 创建SSH对象  
    ssh = paramiko.SSHClient()  
    # 允许连接不在know_hosts文件中的主机  
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
    # 连接服务器  
    ssh.connect(hostname, port, username, password)  
  
    # 使用with语句确保SCPClient正确关闭  
    with SCPClient(ssh.get_transport()) as scp:  
        # 下载文件  
        scp.get(remote_path, local_path)  
    # 关闭连接  
    ssh.close()  
def scp_put(hostname, port, username, password, remote_path, local_path):  
    # 创建SSH对象  
    ssh = paramiko.SSHClient()  
    # 允许连接不在know_hosts文件中的主机  
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
    # 连接服务器  
    ssh.connect(hostname, port, username, password)  

    with SCPClient(ssh.get_transport()) as scp:   
        scp.put(local_path,remote_path)  
    # 关闭连接  

    ssh.close()  


def remote_cmd(ip,port, user,password,cmd):
    """
    多次执行命令不建议多次调用，不快
    
    """
    # 创建SSH对象  
    ssh = paramiko.SSHClient()  
    
    # 允许连接不在know_hosts文件中的主机  
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
    
    # 连接服务器  
    ssh.connect(ip,port, user,password)  
    
    # 创建一个SSH session  
    stdin, stdout, stderr = ssh.exec_command(cmd)  
    
    # 获取命令结果  
    # print(stdout.read().decode())  
    
    # 关闭连接  
    ssh.close()

def sftp_download_folder(sftp,scp, remote_folder, local_folder):  
    """  
    递归下载SFTP服务器上的文件夹到本地。  
    :param sftp: SFTPClient对象  
    :param remote_folder: 远程文件夹路径  
    :param local_folder: 本地文件夹路径  
    """  
    # # 确保本地文件夹存在  
    # if not os.path.exists(local_folder):  
    #     os.makedirs(local_folder)  
  
    # 遍历远程文件夹  
    for filename in sftp.listdir(remote_folder):  
        remote_path =remote_folder+"/"+filename #os.path.join(remote_folder, filename)  
        # local_path = local_folder+"/"+filename#os.path.join(local_folder, filename)  
        # print(sftp.stat(remote_path).st_mode)
  
        # 检查是否为目录  
        if stat.S_ISDIR(sftp.stat(remote_path).st_mode):  # 使用stat模块的S_ISDIR函数检查是否为目录  
            local_path = local_folder+"/"+filename
            print(f"是目录: {remote_path}")
                # 确保本地文件夹存在  
            if not os.path.exists(local_path):  
                os.makedirs(local_path)  
            remote_cmd(target_ip,target_port,target_user,target_password,f"sudo chomd 777 {remote_path}/*")
            sftp_download_folder(sftp,scp, remote_path, local_path)  
        # 检查是否为文件（不是目录）  
        elif stat.S_ISREG(sftp.stat(remote_path).st_mode):  # 使用stat模块的S_ISREG函数检查是否为普通文件  
            local_path = local_folder
            print(f"是文件: {remote_path} ||{local_path}")
            scp.get(remote_path, local_path)  


def scp_downloads(hostname, port, username, password, remote_path, local_path):  
    # 创建SSH对象  
    ssh = paramiko.SSHClient()  
    # 允许连接不在know_hosts文件中的主机  
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
    # 连接服务器  
    ssh.connect(hostname, port, username, password)  
    sftp = ssh.open_sftp()  
    # 使用with语句确保SCPClient正确关闭  
    with SCPClient(ssh.get_transport()) as scp:  
        # 下载文件  
        sftp_download_folder(sftp,scp,remote_path, local_path)  
    # 关闭连接  
    sftp.close()  
    ssh.close()  
def scp_puts(hostname, port, username, password, remote_path, local_path):  
    # 创建SSH对象  
    ssh = paramiko.SSHClient()  
    # 允许连接不在know_hosts文件中的主机  
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
    # 连接服务器  
    ssh.connect(hostname, port, username, password)  
    sftp = ssh.open_sftp()  
    with SCPClient(ssh.get_transport()) as scp:   
        scp.put(local_path,remote_path)  
    # 关闭连接  
    sftp.close()  
    ssh.close()  

    
if __name__ == '__main__':  
    source_ip = "192.168.11.172"
    source_port = 22
    source_user = "hujingxuan"
    source_password = "hujingxuan"

    # filepath="/home/hujingxuan/tmp/tmp.5DXyTa6nsa/cmake-build-release/eventest"
    source_file ="/home/hujingxuan/tmp/tmp.V0gwzMhox1/cmake-build-release"
    filename = "eventTriggeredSrv"

    # source_file = "/home/hujingxuan/tmp/tmp.V0gwzMhox1/out-aarch64/"
    # filename = "esccu-eventtriggeredsrv_2.0.3.9_arm64.deb"

    # source_file = "/home/hujingxuan/tmp/tmp.0Bq7opartM/out-aarch64/"
    # filename = "esccu-libplugprot-io-gold-cmu_1.0.29_arm64.deb"

    # source_file = "/home/hujingxuan/tmp/tmp.0Bq7opartM/out-aarch64/libplugprot-io-gold-v1/app/aarch64/escu/device/plug/prot/lib/"
    # filename = "libplugprot-io-gold-v1.so"


    target_ip = "192.168.28.234"
    target_port = 22
    target_user = "gold"
    target_password = "gold"
    target_file ="/app/aarch64/lems/service/eventTriggeredSrv"


    # target_ip = "192.168.28.228"
    # target_port = 22
    # target_user = "gold"
    # target_password = "gold"
    # target_file ="/app/aarch64/lems/service/test"
    print("开始执行")


    outfolder = "./mid"



    os.makedirs(outfolder,exist_ok=True)  

    source_file 


    # scp_downloads(target_ip, target_port, target_user, target_password, target_file+"/config", outfolder+"/config")

    remote_cmd(target_ip,target_port,target_user,target_password,f"sudo chmod 777 {target_file}")

    try:  
        scp_download(source_ip, source_port,source_user,source_password,source_file+"/"+filename, outfolder)
        print(f"文件下载成功。{source_file}/{filename}")  
    except Exception as e:  
        print(f"文件下载发生错误：{e}")

    remote_cmd(target_ip,target_port,target_user,target_password,f"sudo su")
    print(f"删除原始 {target_file}/{filename} 文件")
    remote_cmd(target_ip,target_port,target_user,target_password,f"rm {target_file}/{filename}")

    try:  
        scp_put(target_ip, target_port,target_user,target_password ,target_file,outfolder+"/"+filename)
        print(f"文件上传成功  {target_file}/{filename}")  
    except Exception as e:  
        print(f"文件上传发生错误：{e}")
    pass
    remote_cmd(target_ip,target_port,target_user,target_password,f"chmod 775 {target_file}/{filename}")
    print(f"chmod 775 {target_file}/{filename} ")


    # scp -r gold@192.168.28.113:/app/aarch64/lems/service/eventTriggeredSrv/config ./
    # chmod 775 $(find ./ -type f)
